package com.gopay.common.metric;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.support.CronTrigger;

import java.util.List;

/**
 * @author ddh02
 * @MetricCronCollector
 * @2017/8/29 8:35  www.gopay.com.cn Inc.All rights reserved.
 */


public class MetricCronCollector {

    private static final Logger logger = LoggerFactory.getLogger(MetricCronCollector.class);

    private String cron;

    private List<MetricSource> metricSources;

    private String transferUrl;

    private boolean execute = true;

    private TaskScheduler scheduler;

    public void collect() {

        scheduler.schedule(new Runnable() {
            @Override
            public void run() {

                if (!execute) {
                    return;
                }

                for(MetricSource metricSource : metricSources){
                    try {
                        metricSource.record(transferUrl);
                    } catch (Exception e){
                        logger.error("指标采集执行异常：{}", e);
                    }
                }

            }
        }, new CronTrigger(cron));

    }

    public void destroy() {
    }

    public String getCron() {
        return cron;
    }

    public void setCron(String cron) {
        this.cron = cron;
    }

    public List<MetricSource> getMetricSources() {
        return metricSources;
    }

    public void setMetricSources(List<MetricSource> metricSources) {
        this.metricSources = metricSources;
    }

    public String getTransferUrl() {
        return transferUrl;
    }

    public void setTransferUrl(String transferUrl) {
        this.transferUrl = transferUrl;
    }

    public boolean isExecute() {
        return execute;
    }

    public void setExecute(boolean execute) {
        this.execute = execute;
    }

    public TaskScheduler getScheduler() {
        return scheduler;
    }

    public void setScheduler(TaskScheduler scheduler) {
        this.scheduler = scheduler;
    }
}
